package com.nmdl.print.utils;

import android.os.Environment;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Download {
    private static String saveDir = "ceitsa";

    public static void downLoadFile(String url, OnDownBack onDownBack) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                if (onDownBack != null) onDownBack.onFail();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String savePath = isExistDir(saveDir);
                File file = new File(savePath, getNameFromUrl(url));
                writeFile(file, response, onDownBack);
            }
        });
    }

    public static void writeFile(File file, Response response, OnDownBack onDownBack) {
        OutputStream outputStream = null;
        InputStream inputStream = response.body().byteStream();
        try {
            outputStream = new FileOutputStream(file);
            int len = 0, readLength = 0;
            byte[] buffer = new byte[1024 * 10];
            int totalLength = (int) response.body().contentLength();
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
                readLength += len;
                int progress = (int) (((float) readLength / (float) totalLength) * 100);
                if (onDownBack != null) onDownBack.onProgress(progress);
                System.out.println("数据写入---------------------current:" + readLength + "  total:" + totalLength + " progress:" + progress);
            }
            if (onDownBack != null) onDownBack.onSuccess(file.getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            if (onDownBack != null) onDownBack.onFail();
        } catch (IOException e) {
            e.printStackTrace();
            if (onDownBack != null) onDownBack.onFail();
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
                if (outputStream != null)
                    outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public interface OnDownBack {
        void onSuccess(String filePath);

        void onProgress(int progress);

        void onFail();
    }

    /**
     * @param saveDir
     * @return
     * @throws IOException 判断下载目录是否存在
     */
    public static String isExistDir(String saveDir) {
        try {
            // 下载位置
            File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
            if (!downloadFile.mkdirs()) {
                downloadFile.createNewFile();
            }
            String savePath = downloadFile.getAbsolutePath();
            return savePath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */
    @NonNull
    public static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }
}
